//
//  RTJChargeController.m
//  RuiTaiJinProject
//
//  Created by jayson on 2018/12/5.
//  Copyright © 2018年 leewei. All rights reserved.
//

#import "RTJChargeController.h"
#import "RTJUserInfoCommntCell.h"
#import "RTJBankTypeListController.h"
#import "RTJForgetPassWordController.h"
#import "RTJQuickPayController.h"
#import "RTJPrepaidRecordsController.h"
#import "RTJChangeBankView.h"

@interface RTJChargeController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tab;

@property (nonatomic,strong) NSString *money;
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSString *idCard;
@property (nonatomic,strong) NSString *bankNum;
@property (nonatomic,strong) NSString *bankID;
@property (nonatomic,strong) NSString *bankName;
@property (nonatomic,strong) NSString *phone;
@property (nonatomic,strong) NSString *reserve_mobile;
@property (nonatomic,assign) BOOL isChange;
@property (nonatomic,strong) UITextField *phoneFld;
@property (nonatomic,assign) BOOL isRealnameBankbinding;//已实名且用快钱进行过充值的银行卡

@property (nonatomic,strong) UITextField *textFld;
@property (nonatomic,strong) NSString *codeStr;
@property (nonatomic,strong) NSString *externalRefNumber;
@property (nonatomic,strong) NSString *token;
@property (nonatomic,strong) UIButton *sendSMSBtn;
@property (nonatomic,strong) NSMutableArray *cardArr;

@property (nonatomic,assign) BOOL isSend;
@property (nonatomic,assign) BOOL bankType;
@property (nonatomic,strong )NSArray *bankData;
@property (nonatomic,strong) NSDictionary *selectBankData;

@end

@implementation RTJChargeController

-(void)viewWillAppear:(BOOL)animated{
    
    [self.tab reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"充值";
    self.navigationController.navigationBarHidden = NO;
    self.tab.tableFooterView=[UIView new];
    self.tab.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tab.keyboardDismissMode = UIScrollViewKeyboardDismissModeNone;
    self.tab.estimatedRowHeight=300;
    
    
    _cardArr  = [NSMutableArray array];
    _bankType = YES;
    
     [self userbanklist];
   
}

-(void)chongzhi{
    
    RTJPrepaidRecordsController *vc = [[RTJPrepaidRecordsController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

//-(void)supportBankCardType{
//
//    [RTJNetWork asyncRequestWithURL:@"user/get_bank" params:nil method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
//
//        if (success) {
//
//            if ([data[@"status"]integerValue] == 1) {
//                NSArray *arr = data[@"data"];
//
//                [self.cardArr addObjectsFromArray:arr];
//
//            }else{
//
//                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"获取银行卡信息失败:%@",data[@"msg"]]];
//
//            }
//
//        }else{
//
//            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
//
//        }
//
//
//
//    }];
//
//}

-(void)userbanklist{
    
    [SVProgressHUD showWithStatus:nil];
    [self.view showEmptyViewWithStr:@"" image:nil callback:nil];
    
    [RTJNetWork asyncRequestWithURL:@"user/bank_list" params:@{@"is_quick":@"1"} method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        [self.view removeEmptyView];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                self.bankData = data[@"data"];
                
                if (self.bankData.count !=0 ) {
                    
                    UIButton *clear=[UIButton buttonWithType:UIButtonTypeSystem];
                    clear.size=CGSizeMake(60, 30);
                    [clear setTitle:@"充值记录" forState:UIControlStateNormal];
                    [clear setTitleColor:[UIColor colorForHex:@"#666666"] forState:UIControlStateNormal];
                    clear.titleLabel.font=[UIFont systemFontOfSize:14];;
                    [clear addTarget:self action:@selector(chongzhi) forControlEvents:UIControlEventTouchUpInside];
                    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:clear];
                    
                }else{
                    
                    UIButton *clear=[UIButton buttonWithType:UIButtonTypeSystem];
                    clear.size=CGSizeMake(60, 30);
                    [clear setTitle:@"支持银行" forState:UIControlStateNormal];
                    [clear setTitleColor:[UIColor colorForHex:@"#666666"] forState:UIControlStateNormal];
                    clear.titleLabel.font= [UIFont systemFontOfSize:14];
                    //    [UIFont fontWithName:@"PingFang-SC-Bold" size:8];
                    [clear addTarget:self action:@selector(chakan) forControlEvents:UIControlEventTouchUpInside];
                    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:clear];
                    
                }
                
                self.isRealnameBankbinding = self.bankData.count!=0 ? YES : NO;
                
//                if (self.isRealnameBankbinding == NO) {
//
//                    //获取快钱支付支持的银行卡列表
//                    [self supportBankCardType];
//                }
                
                [self.tab reloadData];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"获取银行卡信息失败:%@",data[@"msg"]]];
                [self.view showEmptyViewWithStr:data[@"msg"] image:[UIImage imageNamed:@"kbylogo"] callback:^{
                    
                    [self userbanklist];
                }];
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            
            [self.view showEmptyViewWithStr:errorMsg image:[UIImage imageNamed:@"kbylogo"] callback:^{
                
                [self userbanklist];
            }];

        }
        
    }];
    
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _isRealnameBankbinding ? 1:7;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewAutomaticDimension;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * ID = @"Cell";
    
        NSInteger idcardpassed = [RTJUserTool getTheUserModel].idcardpassed;

        RTJUserInfoCommntCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (_isRealnameBankbinding) {
        
        if (indexPath.row == 0) {
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][3];

            }
            
            cell.moneyTexFld.text = _money;
            cell.moneyTexFld.tag = 100;
            cell.yuLiuTxTFld.tag = 1000;
            _phoneFld = cell.yuLiuTxTFld;
            cell.moneyTexFld.delegate = self;
            cell.yuLiuTxTFld.delegate = self;
            
            if (_selectBankData!=nil) {
                
                    NSString *bankStr = [NSString stringWithFormat:@"%@",_selectBankData[@"bankcard"]];
                    bankStr = [bankStr substringFromIndex:bankStr.length-4];
                    
                    cell.bankTypeLab.text = [NSString stringWithFormat:@"%@(尾号%@)",_selectBankData[@"name"],bankStr];
                    _bankNum = [NSString stringWithFormat:@"%@",_selectBankData[@"bankcard"]];
                    if (!_isChange) {
                        
                        NSString *phone = [NSString stringWithFormat:@"%@",_selectBankData[@"reserve_mobile"]];
                        
                        if ([phone isEqualToString:@"<null>"]) {
                            
                            cell.yuLiuTxTFld.text = @"";
                            
                        }else{
                            
                            _reserve_mobile = phone;
                            cell.yuLiuTxTFld.text = [Apputil replaceStringWithAsterisk:phone startLocation:3 lenght:phone.length-7];
                            
                        }
                        
                    }else{
                        
                        cell.yuLiuTxTFld.text = _reserve_mobile;
                        
                    }
                    
                
            }else{
                
                if (_bankData.count!=0) {
                    
                    NSString *bankStr = [NSString stringWithFormat:@"%@",_bankData[0][@"bankcard"]];
                    bankStr = [bankStr substringFromIndex:bankStr.length-4];
                    
                    cell.bankTypeLab.text = [NSString stringWithFormat:@"%@(尾号%@)",_bankData[0][@"name"],bankStr];
                    _bankNum = [NSString stringWithFormat:@"%@",_bankData[0][@"bankcard"]];

                    if (!_isChange) {
                        
                        NSString *phone = [NSString stringWithFormat:@"%@",_bankData[0][@"reserve_mobile"]];
                        
                        if ([phone isEqualToString:@"<null>"]) {
                            
                            cell.yuLiuTxTFld.text = @"";
                            
                        }else{
                            
                            _reserve_mobile = phone;
                            cell.yuLiuTxTFld.text = [Apputil replaceStringWithAsterisk:phone startLocation:3 lenght:phone.length-7];
                            
                        }
                        
                    }else{
                        
                        cell.yuLiuTxTFld.text = _reserve_mobile;
                        
                    }
                    
                }
                
            }
            
            [cell.xiugaiBtn addTarget:self action:@selector(xiugaiPhone) forControlEvents:UIControlEventTouchUpInside];
            [cell.changeBankBtn addTarget:self action:@selector(changBankCard) forControlEvents:UIControlEventTouchUpInside];

            cell.remainLab.text = [NSString stringWithFormat:@"账户可用金额：%@ 元",[RTJUserTool getTheUserModel].money_format];
            [cell.sureBtn addTarget:self action:@selector(Confirmprepaidphone) forControlEvents:UIControlEventTouchUpInside];
            
        }
        
    }else{
        
        if (indexPath.row == 0) {
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
                
            }
            cell.titleLab.text = @"金额:";
            cell.textFld.delegate = self;
            cell.textFld.placeholder = @"请输入你的充值金额，100起充";
            cell.textFld.keyboardType = UIKeyboardTypeNumberPad;
            cell.textFld.text = _money;
            cell.textFld.tag = 10;
            
        }
        
        
        else if (indexPath.row == 1){
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
                
            }
            cell.titleLab.text = @"姓名:";
            cell.textFld.delegate = self;
            cell.textFld.placeholder = @"请输入你的姓名";
            cell.textFld.tag = 20;
            cell.textFld.userInteractionEnabled = idcardpassed == 1 ? NO : YES;
            cell.textFld.text = idcardpassed == 1 ? [Apputil replaceStringWithAsterisk:[RTJUserTool getTheUserModel].real_name startLocation:1 lenght:[RTJUserTool getTheUserModel].real_name.length -1]:_name;
            
        }else if (indexPath.row == 2){
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
                
            }
            cell.textFld.tag = 30;
            cell.textFld.delegate = self;
            cell.titleLab.text = @"身份证号码:";
            cell.textFld.placeholder = @"请输入身份证号码";
            cell.textFld.userInteractionEnabled = idcardpassed == 1 ? NO : YES;
            
            NSString *idno = [NSString stringWithFormat:@"%ld",(long)[RTJUserTool getTheUserModel].idno];
            cell.textFld.text = idcardpassed == 1 ? [NSString stringWithFormat:@"%@",[Apputil replaceStringWithAsterisk:idno startLocation:4 lenght:idno.length -8]]:_idCard;
            
        }else if (indexPath.row == 3){
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
                
            }
            cell.titleLab.text = @"银行卡号:";
            cell.textFld.placeholder = @"请输入对应身份证的银行卡号";
            cell.textFld.tag = 40;
            cell.textFld.delegate = self;
            cell.textFld.userInteractionEnabled =  YES;
            cell.textFld.text = _bankNum;
            
        }else if (indexPath.row == 4){
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
                
            }
            cell.titleLab.text = @"银行名称:";
            cell.textFld.placeholder = @"请选择银行";
            cell.textFld.delegate = self;
            cell.textFld.text = _bankName;
            cell.textFld.userInteractionEnabled = NO;
            
        }else if (indexPath.row == 5){
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][0];
                
            }
            cell.textFld.tag = 50;
            cell.textFld.delegate = self;
            cell.titleLab.text = @"手机号码:";
            cell.textFld.placeholder = @"请输入银行卡预留手机号码";
            cell.textFld.text = _phone;
            
        }else{
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCommntCell" owner:self options:nil][1];
                
            }
            [cell.bindBtn addTarget:self action:@selector(bindAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell.bindBtn setTitle:@"确认充值" forState:UIControlStateNormal];
        }
        
    }
    
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return  cell;
    
}


-(void)chakan{
    
    RTJBankTypeListController *vc =[[RTJBankTypeListController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    
    _textFld = textField;
    
    if (textField.tag == 10) {
        
        _money = textField.text;
        
    }else if (textField.tag == 20) {
        
        _name = textField.text;
        
    }else if (textField.tag == 30){
        
        _idCard = textField.text;
        
    }else if (textField.tag == 40){
   
        _bankNum = textField.text;

        
        if (_bankNum.length!=0) {
            
            //验证银行卡类型
            [self verifyBankCardType:_bankNum];
            
        }
        
    }else if (textField.tag == 50){

            _phone = textField.text;

        
    }else if(textField.tag == 1000){
        
        _isChange = YES;
        _reserve_mobile = textField.text;
        
        [self.tab reloadData];
        
    }else{
        
        _money = textField.text;

    }
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
      _textFld = textField;
}

//验证银行卡类型
-(void)verifyBankCardType:(NSString *)bankNum{
    
    [RTJNetWork asyncRequestWithURL:@"query/get_bank_info" params:@{@"bankcard":bankNum} method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                self.bankName = data[@"data"][@"bank_name"];
                self.bankID = [NSString stringWithFormat:@"%@",data[@"data"][@"bank_id"]];
                self.bankType = YES;
                [self.tab reloadData];
                
//                [self.cardArr enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
//
//                    if([dic[@"id"]isEqualToString:ids]){
//
//                        self.bankName = data[@"data"][@"bank_name"];
//                        self.bankID = [NSString stringWithFormat:@"%@",data[@"data"][@"bank_id"]];
//                        self.bankType = YES;
//                        [self.tab reloadData];
//
//                        *stop = YES;
//
//                    }else{
//
//                        self.bankName = @"";
//                        self.bankID = @"";
//                        self.bankType = NO;
//                        [self.tab reloadData];
//
//                        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"暂不支持该银行卡"]];
//
//                    }
                
//                }];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"验正银行卡类型失败:%@",data[@"msg"]]];
                self.bankName = @"";
                self.bankID = @"";
                self.bankType = NO;
                [self.tab reloadData];
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"验正银行卡类型失败:%@",errorMsg]];
            self.bankName = @"";
            self.bankID = @"";
            self.bankType = NO;
            [self.tab reloadData];
        }
        
    }];
    
}

-(void)Confirmprepaidphone{
    
    [_textFld resignFirstResponder];

    if (_money.length == 0 ) {

        [SVProgressHUD showErrorWithStatus:@"请输入充值金额"];
        return;
    }

    NSInteger money = [_money integerValue];
    if (money<100) {

        [SVProgressHUD showErrorWithStatus:@"充值金额，100起充"];
        return;
    }
    
    if (_reserve_mobile.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"请输入您的银行卡预留电话"];
        return;
    }
    
    [self ConfirmPrepaidPhone:@{@"amount":_money,@"mobile":_reserve_mobile,@"bank_card":_bankNum}];
    
}

-(void)xiugaiPhone{
    
    _isChange = YES;
    _reserve_mobile = @"";
    [_phoneFld becomeFirstResponder];
    
}


-(void)bindAction:(UIButton *)btn{
   
    [_textFld resignFirstResponder];
    
    [self surePay];


}

-(void)surePay{
    
    [SVProgressHUD showWithStatus:nil];
    NSDictionary *dic = nil;
    
    NSInteger idcardpassed = [RTJUserTool getTheUserModel].idcardpassed;
    
    if (_money.length == 0 ) {
        
        [SVProgressHUD showErrorWithStatus:@"请输入充值金额"];
        return;
    }
    
    NSInteger money = [_money integerValue];
    if (money<100) {

        [SVProgressHUD showErrorWithStatus:@"充值金额，100起充"];
        return;
    }
    
    if (_bankNum.length == 0 ) {
        
        [SVProgressHUD showErrorWithStatus:@"请填写银行卡卡号"];
        return;
    }
    
    if (_bankNum.length >19) {
        
        [SVProgressHUD showErrorWithStatus:@"请正确填写银行卡卡号"];
        return;
    }
    
    if (15>_bankNum.length) {
        
        [SVProgressHUD showErrorWithStatus:@"请正确填写银行卡卡号"];
        return;
    }
    
    
    if (_bankID.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"请正确选择银行类型"];
        return;
    }
    
    if (_phone.length == 0 ) {
        
        [SVProgressHUD showErrorWithStatus:@"请填写手机号"];
        return;
    }
    
    if (![Apputil validatePhoneWithString:_phone] ) {
        
        [SVProgressHUD showErrorWithStatus:@"请正确填写手机号"];
        return;
    }
    
    if (idcardpassed == 1) {//已实名
        
        dic = @{
                @"amount":_money,
                @"bank_card":_bankNum,
                @"bank_id":_bankID,
                @"mobile":_phone
                };
        
    }else{
        //未实名
        
        if (_name.length == 0 ) {
            
            [SVProgressHUD showErrorWithStatus:@"请填写姓名"];
            return;
        }
        
        if (_idCard.length == 0 ) {
            
            [SVProgressHUD showErrorWithStatus:@"请填写身份证号"];
            return;
        }
        
        if (_idCard.length != 18 ) {
            
            [SVProgressHUD showErrorWithStatus:@"请正确填写身份证号"];
            return;
        }
        
        dic = @{
                @"amount":_money,
                @"bank_card":_bankNum,
                @"bank_id":_bankID,
                @"mobile":_phone,
                @"real_name":_name,
                @"idno":_idCard
                };
    }
    
    [self ConfirmPrepaidPhone:dic];
    
}

-(void)ConfirmPrepaidPhone:(NSDictionary *)dic{
    
    /*user/get_code_for_kq :快捷支付第一步：获取快钱验证码
     姓名，未实名时必需填写
     身份证号，未实名时必需填写
     */
    
    [RTJNetWork asyncRequestWithURL:@"user/get_code_for_kq" params:dic method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                [SVProgressHUD showSuccessWithStatus:@"验证短信已经发送，请注意查收"];
                
                RTJQuickPayController *payVC = [[RTJQuickPayController alloc]init];
                payVC.title = @"付款确认";
                payVC.dic = dic;
                payVC.order_sn = [NSString stringWithFormat:@"%@",data[@"data"][@"order_sn"]];
                payVC.money = self.money;
                [self.navigationController pushViewController:payVC animated:YES];
                
                
            }else{
                
                NSString *str = [NSString stringWithFormat:@"%@",data[@"msg"]];
                
                if ([str isEqualToString:@"输入参数验证错误"]) {
                    
                    str = @"暂不支持该银行卡充值";
                }
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",str]];
                
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            
        }
        
    }];
    
}


//-(void)bankName:(NSString *)bankName bankID:(NSString *)bankID{
//
//    if ([bankID isEqualToString:_bankID]) {
//
//        self.bankType = YES;
//
//        _bankName = bankName;
//        _bankID = bankID;
//        [self.tab reloadData];
//
//    }else{
//
//        self.bankType = NO;
//
//        [SVProgressHUD showErrorWithStatus:@"银行卡类型与银行卡号不匹配，请正确选择"];
//        _bankName = @"";
//        _bankID = @"";
//        [self.tab reloadData];
//    }
//
//}

-(void)changBankCard{
    
    RTJChangeBankView *bankView = [[RTJChangeBankView alloc]initWithFrame:self.view.bounds];
    bankView.data = _bankData;
    
    [bankView setBankClick:^(NSDictionary * _Nonnull dic) {
        
        self.selectBankData = dic;
        [self.tab reloadData];
        
    }];
    bankView.VC = self;
    [bankView viewShow];
   
   
    
}


@end
